#include <chrono>

#include "rclcpp/rclcpp.hpp"
#include "example_interfaces/srv/add_two_ints.hpp"

using namespace std::chrono_literals;

class ServiceClient_01:public rclcpp::Node{
public:
    ServiceClient_01(std::string name):Node(name){
        RCLCPP_INFO(this->get_logger(),"I am service client 01: %s",name.c_str());
        client_=this->create_client<example_interfaces::srv::AddTwoInts>("add_tow_ints_srv");
    }

    auto sendRequest(std::shared_ptr<example_interfaces::srv::AddTwoInts_Request> request){
        //1,等待server上线
        while(!client_->wait_for_service(1s)){
            //failed,检查rclcpp状态
            if(!rclcpp::ok()){
                RCLCPP_INFO(this->get_logger(),"interrupted while waiting for service.");
                break;
            }
            RCLCPP_INFO(this->get_logger(),"Wainting for the server to work...");
        }
        //2,构造请求
        // int n1=0,n2=0;
        // std::cin>>n1>>n2;
        // auto request=std::make_shared<example_interfaces::srv::AddTwoInts_Request>();
        // request->a=n1;
        // request->b=n2;
        //3,发送请求
        auto result=client_->async_send_request(request);
        return result;
    }

    // void responseCallback(example_interfaces::srv::AddTwoInts::Response::SharedPtr result){
    //     //auto response=result_future.get();
    //     RCLCPP_INFO(this->get_logger(),"Caculate result: %ld",result->sum);
    // }

    void responseCallback(std::future<example_interfaces::srv::AddTwoInts::Response::SharedPtr> result_future){
        auto response=result_future.get();
        RCLCPP_INFO(this->get_logger(),"Caculate result: %ld",response->sum);
    }
    

private:
    rclcpp::Client<example_interfaces::srv::AddTwoInts>::SharedPtr client_{};

    //回调函数
    // void _responseCallback(rclcpp::Client<example_interfaces::srv::AddTwoInts>::SharedFuture result_future){
    //     auto response=result_future.get();
    //     RCLCPP_INFO(this->get_logger(),"Caculate result: %ld",response->sum);
    // }
};

int main(int argc,char** argv){
    rclcpp::init(argc,argv);
    auto node=std::make_shared<ServiceClient_01>("service_client_01");
    auto request=std::make_shared<example_interfaces::srv::AddTwoInts_Request>();
    std::cin>>request->a>>request->b;
    auto result=node->sendRequest(request);
    //rclcpp::spin(node);
    if(rclcpp::spin_until_future_complete(node,result)==rclcpp::FutureReturnCode::SUCCESS){
        //node->responseCallback(result.future.get());
        node->responseCallback(std::move(result.future));
    }
    rclcpp::shutdown();
    return 0;
}